'use client';

import { useState, useEffect } from 'react';
import Sidebar from '@/components/Sidebar';
import { Category, STORAGE_KEYS, DEFAULT_CATEGORIES } from '@/types';

export default function Categories() {
  const [darkMode, setDarkMode] = useState(false);
  const [username, setUsername] = useState('用户');
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [categories, setCategories] = useState<Category[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showAddForm, setShowAddForm] = useState(false);
  const [newCategoryName, setNewCategoryName] = useState('');
  const [newCategoryColor, setNewCategoryColor] = useState('#6b7280');
  const [isEditing, setIsEditing] = useState<string | null>(null);
  const [editName, setEditName] = useState('');
  const [editColor, setEditColor] = useState('');

  // 初始化主题和加载数据
  useEffect(() => {
    // 检查本地存储的主题设置
    const savedTheme = localStorage.getItem('theme');
    const prefersColorScheme = window.matchMedia('(prefers-color-scheme: dark)');
    const systemPrefersDark = prefersColorScheme.matches;

    // 根据保存的设置或系统偏好设置主题
    if (savedTheme === 'light') {
      // 用户明确设置为亮色
      setDarkMode(false);
      document.documentElement.classList.remove('dark');
    } else if (savedTheme === 'dark') {
      // 用户明确设置为暗色
      setDarkMode(true);
      document.documentElement.classList.add('dark');
    } else {
      // 没有保存过主题，根据系统偏好设置
      setDarkMode(systemPrefersDark);
      if (systemPrefersDark) {
        document.documentElement.classList.add('dark');
        localStorage.setItem('theme', 'dark');
      } else {
        document.documentElement.classList.remove('dark');
        localStorage.setItem('theme', 'light');
      }
    }

    // 监听主题变化事件（从其他页面触发的）
    const handleThemeChange = (e: CustomEvent) => {
      const newTheme = e.detail.theme;
      setDarkMode(newTheme === 'dark');
      if (newTheme === 'dark') {
        document.documentElement.classList.add('dark');
      } else {
        document.documentElement.classList.remove('dark');
      }
    };

    window.addEventListener('themeChange', handleThemeChange as EventListener);
    
    // 加载分类
    const loadCategories = () => {
      setIsLoading(true);
      
      try {
        // 从localStorage获取分类
        const savedCategories = localStorage.getItem(STORAGE_KEYS.CATEGORIES);
        
        if (savedCategories) {
          setCategories(JSON.parse(savedCategories));
        } else {
          // 如果没有保存的分类，使用默认分类
          setCategories(DEFAULT_CATEGORIES);
          localStorage.setItem(STORAGE_KEYS.CATEGORIES, JSON.stringify(DEFAULT_CATEGORIES));
        }
      } catch (error) {
        console.error('加载分类失败:', error);
        setCategories(DEFAULT_CATEGORIES);
      } finally {
        setIsLoading(false);
      }
    };
    
    loadCategories();
    
    // 加载用户名
    const savedUsername = localStorage.getItem(STORAGE_KEYS.USERNAME);
    if (savedUsername) {
      setUsername(savedUsername);
    }
    
    return () => {
      window.removeEventListener('themeChange', handleThemeChange as EventListener);
    };
  }, []);

  // 添加新分类
  const addCategory = () => {
    if (!newCategoryName.trim()) return;
    
    const newId = `category_${Date.now()}`;
    const newCategory: Category = {
      id: newId,
      name: newCategoryName.trim(),
      color: newCategoryColor
    };
    
    const updatedCategories = [...categories, newCategory];
    setCategories(updatedCategories);
    localStorage.setItem(STORAGE_KEYS.CATEGORIES, JSON.stringify(updatedCategories));
    
    // 重置表单
    setNewCategoryName('');
    setNewCategoryColor('#6b7280');
    setShowAddForm(false);
  };

  // 更新分类
  const updateCategory = (id: string) => {
    if (!editName.trim() || !isEditing) return;
    
    const updatedCategories = categories.map(cat => 
      cat.id === id ? { ...cat, name: editName.trim(), color: editColor } : cat
    );
    
    setCategories(updatedCategories);
    localStorage.setItem(STORAGE_KEYS.CATEGORIES, JSON.stringify(updatedCategories));
    
    // 重置编辑状态
    setIsEditing(null);
    setEditName('');
    setEditColor('');
  };

  // 删除分类
  const deleteCategory = (id: string) => {
    // 确认删除
    if (!confirm('确定要删除此分类吗？该分类下的视频将变为未分类。')) return;
    
    const updatedCategories = categories.filter(cat => cat.id !== id);
    setCategories(updatedCategories);
    localStorage.setItem(STORAGE_KEYS.CATEGORIES, JSON.stringify(updatedCategories));
  };

  // 开始编辑分类
  const startEditing = (category: Category) => {
    setIsEditing(category.id);
    setEditName(category.name);
    setEditColor(category.color);
  };

  // 取消编辑
  const cancelEditing = () => {
    setIsEditing(null);
    setEditName('');
    setEditColor('');
  };

  // 重置为默认分类
  const resetToDefault = () => {
    if (!confirm('确定要重置为默认分类吗？这将删除所有自定义分类。')) return;
    
    setCategories(DEFAULT_CATEGORIES);
    localStorage.setItem(STORAGE_KEYS.CATEGORIES, JSON.stringify(DEFAULT_CATEGORIES));
  };

  return (
    <div className="flex h-full">
      {/* 侧边栏 */}
      <Sidebar 
        darkMode={darkMode} 
        username={username} 
        isOpen={sidebarOpen} 
        onToggle={() => setSidebarOpen(!sidebarOpen)} 
      />
      
      {/* 主内容区 */}
      <div className={`flex-1 md:ml-64 bg-white dark:bg-black min-h-screen text-black dark:text-white transition-all duration-300 ${
        sidebarOpen ? 'md:translate-x-0' : 'translate-x-0'
      }`}>
        {/* 顶部导航 */}
        <nav className="border-b border-gray-100 dark:border-gray-800">
          <div className="max-w-5xl mx-auto px-4 py-4 flex justify-between items-center">
            <div className="flex items-center">
              {/* 移动端汉堡菜单按钮 */}
              <button
                className="md:hidden mr-4 text-gray-600 dark:text-gray-400"
                onClick={() => setSidebarOpen(!sidebarOpen)}
                aria-label="打开菜单"
              >
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
                </svg>
              </button>
              <h1 className="text-xl font-medium">视频分类</h1>
            </div>
          </div>
        </nav>

        <main className="max-w-5xl mx-auto px-4 py-8">
          <div className="mb-6">
            <p className="text-gray-600 dark:text-gray-400 mb-4">
              在这里管理视频分类，您可以添加、编辑或删除分类。这些分类可以在历史记录和收藏页面中使用。
            </p>
            
            <div className="flex flex-wrap gap-3 mb-6">
              <button 
                onClick={() => setShowAddForm(!showAddForm)}
                className="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg shadow-sm flex items-center"
              >
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5 mr-1">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
                </svg>
                添加新分类
              </button>
              
              <button 
                onClick={resetToDefault}
                className="px-4 py-2 bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200 rounded-lg shadow-sm flex items-center"
              >
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5 mr-1">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99" />
                </svg>
                重置为默认
              </button>
            </div>
            
            {/* 添加分类表单 */}
            {showAddForm && (
              <div className="mb-6 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
                <h3 className="text-lg font-medium mb-3">添加新分类</h3>
                <div className="mb-3">
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">分类名称</label>
                  <input
                    type="text"
                    placeholder="输入分类名称"
                    value={newCategoryName}
                    onChange={(e) => setNewCategoryName(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm bg-white dark:bg-gray-900 text-black dark:text-white focus:ring-blue-500 focus:border-blue-500"
                    maxLength={10}
                  />
                </div>
                <div className="mb-4">
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">分类颜色</label>
                  <div className="flex items-center gap-3">
                    <input
                      type="color"
                      value={newCategoryColor}
                      onChange={(e) => setNewCategoryColor(e.target.value)}
                      className="w-10 h-10 border-0 p-0 bg-transparent"
                    />
                    <span className="text-sm text-gray-500 dark:text-gray-400">{newCategoryColor}</span>
                  </div>
                </div>
                <div className="flex gap-2">
                  <button
                    onClick={addCategory}
                    disabled={!newCategoryName.trim()}
                    className="px-4 py-2 bg-blue-500 hover:bg-blue-600 disabled:bg-gray-400 disabled:cursor-not-allowed text-white rounded-md"
                  >
                    添加
                  </button>
                  <button
                    onClick={() => setShowAddForm(false)}
                    className="px-4 py-2 bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200 rounded-md"
                  >
                    取消
                  </button>
                </div>
              </div>
            )}
          </div>
          
          {/* 分类列表 */}
          <div className="bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 shadow-sm overflow-hidden">
            <div className="px-4 py-3 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
              <h3 className="font-medium">所有分类</h3>
            </div>
            
            {isLoading ? (
              <div className="p-6 text-center text-gray-500">
                加载中...
              </div>
            ) : categories.length === 0 ? (
              <div className="p-6 text-center text-gray-500">
                暂无分类，请添加新分类。
              </div>
            ) : (
              <ul className="divide-y divide-gray-200 dark:divide-gray-800">
                {categories.map(category => (
                  <li key={category.id} className="p-4 hover:bg-gray-50 dark:hover:bg-gray-800">
                    {isEditing === category.id ? (
                      <div className="flex flex-col gap-3">
                        <div>
                          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">分类名称</label>
                          <input
                            type="text"
                            value={editName}
                            onChange={(e) => setEditName(e.target.value)}
                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm bg-white dark:bg-gray-900 text-black dark:text-white focus:ring-blue-500 focus:border-blue-500"
                            maxLength={10}
                          />
                        </div>
                        <div>
                          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">分类颜色</label>
                          <div className="flex items-center gap-3">
                            <input
                              type="color"
                              value={editColor}
                              onChange={(e) => setEditColor(e.target.value)}
                              className="w-8 h-8 border-0 p-0 bg-transparent"
                            />
                            <span className="text-sm text-gray-500 dark:text-gray-400">{editColor}</span>
                          </div>
                        </div>
                        <div className="flex gap-2 mt-2">
                          <button
                            onClick={() => updateCategory(category.id)}
                            disabled={!editName.trim()}
                            className="px-3 py-1 text-sm bg-green-500 hover:bg-green-600 disabled:bg-gray-400 disabled:cursor-not-allowed text-white rounded-md"
                          >
                            保存
                          </button>
                          <button
                            onClick={cancelEditing}
                            className="px-3 py-1 text-sm bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200 rounded-md"
                          >
                            取消
                          </button>
                        </div>
                      </div>
                    ) : (
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <span 
                            className="w-6 h-6 rounded-full flex-shrink-0" 
                            style={{ backgroundColor: category.color }}
                            title={category.color}
                          />
                          <span className="font-medium text-lg">{category.name}</span>
                        </div>
                        <div className="flex gap-2">
                          <button
                            onClick={() => startEditing(category)}
                            className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300"
                            title="编辑"
                          >
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                              <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931z" />
                            </svg>
                          </button>
                          <button
                            onClick={() => deleteCategory(category.id)}
                            className="p-2 text-gray-500 hover:text-red-500"
                            title="删除"
                          >
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                              <path strokeLinecap="round" strokeLinejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
                            </svg>
                          </button>
                        </div>
                      </div>
                    )}
                  </li>
                ))}
              </ul>
            )}
          </div>
        </main>

        {/* 页脚 */}
        <footer className="border-t border-gray-100 dark:border-gray-800 py-6 mt-12">
          <div className="max-w-5xl mx-auto px-4 text-center text-sm text-gray-500 dark:text-gray-400">
            <p>本工具仅用于学习和研究，请勿用于非法用途</p>
          </div>
        </footer>
      </div>
    </div>
  );
} 